const express = require("express")
const router = express.Router()
const adminDB = require("../../db/admin")
const jwt = require("jsonwebtoken")
const activityDB = require("../../db/activity")

// 密钥
const cort = "coderxinxin2022-04-15"

// 用户ID
let userInfoID = ""

// 身份鉴权
// 权限鉴别 鉴别是否为管理员
router.use(async (req, res, next) => {
  try {
    // 校验token
    // 获取请求头里面的token
    let token = (req.headers.authorization || "").slice(7)
    let info = null
    // 捕获错误
    try {
      info = jwt.verify(token, cort)
      const doc = await adminDB.findById(info._id)
      // 检测身份
      if (!doc.admintor)
        return res.send({
          code: 4,
          mes: "您不具有该权限",
        })
      if (!doc)
        return res.send({
          code: 4,
          mes: "系统检测到该账号已被注销",
        })
      // 检测密码是否更新
      if (info.pass !== doc.pass)
        return res.send({
          code: 4,
          mes: "密码已更新,请重新登录",
        })
      userInfoID = doc._id
      next()
    } catch (error) {
      console.log(error)
      return res.send({
        code: 4,
        mes: "登录信息已过期,请重新登录",
      })
    }
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 添加活动
router.post("/add", async (req, res) => {
  try {
    const { name, startTime, endTime, place, des } = req.body
    if (!name.trim())
      return res.send({
        code: 2,
        mes: "请输入活动名称",
      })
    if (!des)
      return res.send({
        code: 2,
        mes: "请输入活动的描述",
      })
    if (!startTime || !endTime)
      return res.send({
        code: 2,
        mes: "请选择活动的时间",
      })
    if (!place)
      return res.send({
        code: 2,
        mes: "请选择活动的地点",
      })
    const participant = (Math.random() * 1000) | 0
    await activityDB.create({
      name,
      startTime,
      endTime,
      place,
      des,
      participant,
      author: userInfoID,
    })
    res.send({
      code: 0,
      mes: "活动新增成功",
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 更新活动
router.post("/update", async (req, res) => {
  try {
    const { activityID, name, des } = req.body
    // 检测活动是否存在
    const doc = await activityDB.findById(activityID)
    if (!doc)
      return res.send({
        code: 2,
        mes: "该活动已被删除",
      })
    if (!name.trim())
      return res.send({
        code: 2,
        mes: "活动名称不能为空",
      })
    if (!des.trim())
      return res.send({
        code: 2,
        mes: "活动描述不能为空",
      })
    await activityDB.findByIdAndUpdate(activityID, {
      name,
      des,
    })
    res.send({
      code: 0,
      mes: "活动更新成功",
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常,请稍后再试",
    })
  }
})

// 获取活动信息
router.get("/getAll", async (req, res) => {
  try {
    const { limit, skip } = req.query
    const activityList = await activityDB
      .find(
        {},
        {},
        {
          sort: {
            time: -1,
          },
          limit: limit * 1,
          skip: skip * 1,
        }
      )
      .populate("author", {
        name: 1,
        avatar: 1,
      })
    const allNums = await (await activityDB.find()).length
    res.send({
      code: 0,
      mes: "获取活动信息列表",
      data: {
        activityList,
        allNums,
      },
    })
  } catch (error) {
    console.log(error)
    res.send({
      coed: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 删除活动
router.post("/delete", async (req, res) => {
  try {
    const { activityID } = req.body
    const doc = await activityDB.findById(activityID)
    if (!doc)
      return res.send({
        code: 2,
        mes: "该活动不存在或已被删除,请刷新后重试",
      })
    await activityDB.findByIdAndRemove(activityID)
    res.send({
      code: 0,
      mes: "活动删除成功",
    })
  } catch (error) {
    console.log(error)
    res.send({
      code: 5,
      mes: "服务器异常,请稍后再试",
    })
  }
})

// 搜索活动
router.get("/search", async (req, res) => {
  try {
    const { name, startTime, endTime, place, limit, skip } = req.query
    let activityList = []
    let allNums = 0
    // 具有时间
    if (startTime != 0) {
      console.log("时间")
      activityList = await activityDB
        .find(
          {
            startTime: { $gte: startTime * 1 },
            endTime: { $lte: endTime * 1 },
            place,
          },
          {}
        )
        .populate("author", {
          name: 1,
          avatar: 1,
        })
      activityList = activityList.filter((item) => item.name.includes(name))
      allNums = activityList.length
      skip == 0
        ? activityList.slice(skip * 1, limit * 1)
        : activityList.slice(skip * 1, limit * 1 + skip * 1)
    }
    // 没有时间
    else {
      activityList = await activityDB
        .find(
          {
            place,
          },
          {}
        )
        .populate("author", {
          name: 1,
          avatar: 1,
        })
      activityList = activityList.filter((item) => item.name.includes(name))
      allNums = activityList.length
      skip == 0
        ? activityList.slice(skip * 1, limit * 1)
        : activityList.slice(skip * 1, limit * 1 + skip * 1)
    }
    res.send({
      code: 0,
      mes: "搜索列表",
      data: {
        activityList,
        allNums,
      },
    })
  } catch (error) {
    console.log(error)
    res.send({
      code: 5,
      mes: "服务器异常,请稍后再试",
    })
  }
})
module.exports = router
